#include "mainwindow.h"
#include "ui_mainwindow.h"



int MainWindow::count = 0;
int MainWindow::TextSum = 1;


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //ui->record->setEnabled(false);
    ui->port->setText("8080"); // 设置默认端口号
    setWindowTitle("服务器") ;
    ui->record->setReadOnly(true);
    printHostIPAddresses();
    ui->sendFile->setEnabled(false);

    // 插入事件过滤器
    KeyFilter* k = new KeyFilter(ui->sendMsg, ui->clean, ui->selFile, ui->sendFile);
    //KeyFilter* k = new KeyFilter;
    ui->msg->installEventFilter(k);

    // 创建AllFolder
    {
        // 获取当前路径
        QDir currentDir = QDir::currentPath();

        // 定义要创建的文件夹名称
        QString folderName = "AllFolder";

        // 构造完整的文件夹路径
        QString folderPath = currentDir.absoluteFilePath(folderName);

        //QDir().mkpath(folderPath);

        // 创建文件夹
        if (QDir().mkpath(folderPath)) {
            ui->record->append("AllFolder created successfully!");
            qDebug() << "文件夹创建成功: " << folderPath;
        } else {
            qDebug() << "文件夹创建失败: " << folderPath;
            ui->record->append("<font color=\"#FF0000\"> AllFolder created failed! </font> ");
        }
    }

    // 实例化监听的服务器对象
    m_s = new QTcpServer(this);

    // 等待客户链接，当有客户端链接到达时，QtcpServer对象可以发射出一个信号(newConnection)
    connect(m_s,&QTcpServer::newConnection,this,[=](){
        QTcpSocket* _tcp = new QTcpSocket;

        _tcp = m_s->nextPendingConnection(); // 通过调用此函数获取一个Socket实例对象

        int i = count;
        count++;
        cNum++;

        m_tcp.push_back(_tcp);

        //ui->C_status->setText("已连接");
        ui->C_status->setText("已连接设备: " + QString::number(cNum));


        // 文件接收:

//        QFile* file = new QFile("revc.txt");
//        // 接收数据
//        connect(_tcp, &QTcpSocket::readyRead,this,[=](){


//            // 判断to do
//            file->open(QFile::Append);

//            // 读出剩余数据
//            QByteArray all = _tcp->readAll();
//            //QString data = QString::fromUtf8(all);
//            //QByteArray all2 = all.toUtf8();

//            file->write("\n" + all);

//            file->close();

//            // 判断数据是否接收完毕
//        });


        // 实例对象什么时候可以接收数据:(检测是否可以接收数据),就是这个实例对象发射readyread信号时
        connect(_tcp,&QTcpSocket::readyRead,this,[=](){
            QByteArray data = _tcp->readAll();
            QString all = QString::fromUtf8(data);
            auto it = all.begin();
            int _m = 1;
            while(*it != ':' && _m < 14)
            {
                it++;
                ++_m;
            }
            if(all.size() - _m <= 51)
            {
                // 消息转发:
                ui->record->append(data); // 追加进通信记录中
                for(int j = 0; j < m_tcp.size(); j++)
                {
                    if(m_tcp[j] != nullptr && j != i)
                    {
                        m_tcp[j]->write(data);
                    }
                }
            }
            else
            {

//                QFile* file = new QFile("revc.txt");

//                // 判断to do
//                file->open(QFile::Append);

//                file->write(data);
//                file->close();

                // 文件转存:
                QString host;
                for(auto e : all)
                {
                    if(e == ":")
                    {
                        //host += e;
                        break;
                    }
                    host += e;
                }
                QString all2 = all.mid(host.size() + 1);
                QByteArray data2 = all2.toUtf8();


                // 创建发送方ip为名的文件夹用于存放文件
                QDir hostDir = QDir::currentPath() + "/AllFolder/" + host;
                QString folderPath = hostDir.absolutePath();

                if(!hostDir.exists())
                {
                    // mkpath函数: 一并连缺失的父目录一并创建
                    if (QDir().mkpath(folderPath)) {
                        ui->record->append("<font color=\"#FF0000\">" + host +
                                           " created successfully！</font> ");
                        qDebug() << "文件夹创建成功: " << folderPath;
                    } else {
                        qDebug() << "文件夹创建失败: " << folderPath;
                        ui->record->append("<font color=\"#FF0000\">" + host +
                                           " created failed！</font> ");
                    }
                }

                QString filetxt = "/" + QString::number(TextSum) + ".txt";

                QFile* file = new QFile(folderPath + filetxt);
                file->open(QFile::Append);
                file->write(data2);
                file->close();

                // 将文字颜色设置为红色
                ui->record->append("<font color=\"#FF0000\">已成功接收 " + host +
                                   " 发送来的文件" + filetxt +"，请及时保存！</font> ");
                TextSum++;

                // 文件转发到其他客户端:
                for(int j = 0; j < m_tcp.size(); j++)
                {
                    if(m_tcp[j] != nullptr && j != i)
                    {
                        m_tcp[j]->write(data);
                    }
                }
            }
        });

        // 断开连接
        connect(_tcp, &QTcpSocket::disconnected,this,[=](){
            _tcp->close();
            _tcp->deleteLater();

            m_tcp[i] = nullptr;
            cNum--;

            ui->C_status->setText("已连接设备: " + QString::number(cNum));
        });


        // 不可用！！！！会切线程断连

        // 使用传参方式传递给子线程
//        RecvFile* subThread = new RecvFile(_tcp);
//        subThread->start();

//        // 因为子线程在此创建，所以子线程发送的信号也要在此处进行处理
//        connect(subThread,&RecvFile::over,this,[=](){
//            subThread->exit();
//            subThread->wait();
//            subThread->deleteLater();
//            ui->record->append( "<font color=\"#FF0000\">已成功接收xxx发送来的文件</font> ");// 将文字颜色设置为红色
//        });

    });



    // 处理状态栏
//    m_status = new QLabel(this);
//    ui->statusBar->addWidget(new QLabel("当前连接状态:"));
//    ui->statusBar->addWidget(m_status);

    //ui->C_status->setText("0");
}

// 删除目录
bool removeDirRecursively(const QString &dirPath) {
    QDir dir(dirPath);

    if (!dir.exists() || !dir.isReadable()) {
        qDebug() << "Directory does not exist:" << dirPath;
        return true; // 如果目录不存在，可以认为“删除”操作是成功的
    }

    if (!dir.isReadable()) {
        qDebug() << "Directory is not readable:" << dirPath;
        return false;
    }

    QFileInfoList fileList = dir.entryInfoList(QDir::NoDotAndDotDot |
                                               QDir::AllDirs | QDir::Files);
    foreach (QFileInfo fileInfo, fileList) {
        if (fileInfo.isDir()) {
            // 递归删除子目录
            if (!removeDirRecursively(fileInfo.absoluteFilePath())) {
                return false;
            }
        } else {
            // 删除文件
            if (!QFile::remove(fileInfo.absoluteFilePath())) {
                qDebug() << "Failed to remove file:" << fileInfo.absoluteFilePath();
                return false;
            }
        }
    }

    // 删除空目录本身
    return dir.rmdir(dir.path());
}

MainWindow::~MainWindow()
{
    QString folderToDelete = QDir::currentPath() + "/AllFolder"; //当前路径 + 指定文件夹

    if (removeDirRecursively(folderToDelete)) {
        qDebug() << "Directory and its contents deleted successfully:" << folderToDelete;
    } else {
        qDebug() << "Failed to delete directory or its contents:" << folderToDelete;
    }

    delete ui;
}


void MainWindow::on_setListen_clicked()
{
    unsigned short port = ui->port->text().toUShort(); // 读出端口号并转换成无符号短整型
    m_s->listen(QHostAddress::Any, port); // 启动监听，绑定IP与端口
    ui->setListen->setText("已启用监听");
    ui->setListen->setEnabled(false); // 绑定后按钮设置为不可用
    // ui->record->append("已启用监听服务!");

    ui->record->append(MyHost + "已启用监听服务");
}

void MainWindow::on_sendMsg_clicked()
{
    QString msg = "Server say: " + ui->msg->toPlainText(); // 将数据以纯文本的方式取出来
    if(msg.size() > 62)
    {
        ui->record->append("<font color=\"#FF0000\">发送字段过长，请重新尝试！(建议五十字符内)</font> ");
    }
    else
    {
        for(int i = 0; i < m_tcp.size(); i++)
        {
            if(m_tcp[i] != nullptr)
            {
                m_tcp[i]->write(msg.toUtf8());
            }
        }
        ui->record->append(msg); // 追加进通信记录中
        ui->msg->setText("");
    }
}

// 获取主机Ipv4地址
void MainWindow::printHostIPAddresses() {
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    foreach (QNetworkInterface interface, interfaces) {
        if (interface.flags().testFlag(QNetworkInterface::IsUp) && !interface.flags().testFlag(QNetworkInterface::IsLoopBack)) {
            QList<QNetworkAddressEntry> entries = interface.addressEntries();
            foreach (QNetworkAddressEntry entry, entries) {
                // 输出所有类型的IP地址
                //qDebug() << "IP Address:" << entry.ip().toString();

                // 如果你只想要IPv4地址，可以添加以下检查
                if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                    //qDebug() << "IPv4 Address:" << entry.ip().toString();
                    MyHost = entry.ip().toString();
                }
            }
        }
    }
}


void MainWindow::on_clean_clicked()
{
    ui->record->setText("");
}


void MainWindow::on_selFile_clicked()
{
    // 弹出选择文件对话框即可
    path = QFileDialog::getOpenFileName(); // 得到某个磁盘文件的绝对路径
    if(path.isEmpty())
    {
        ui->sendFile->setEnabled(false);
    }
    else
    {
        ui->msg->setText(path);
        ui->sendFile->setEnabled(true);
    }
}

void MainWindow::on_sendFile_clicked()
{
    if(path != "")
    {
        QFile file(path);
        bool IsSend = false;
        file.open(QFile::ReadOnly);
        QString host = "Server:";
        QByteArray all = host.toUtf8();
        all += file.readAll();

        // 多客户端发送
        for(int i = 0; i < m_tcp.size(); i++)
        {
            if(m_tcp[i] != nullptr)
            {
                m_tcp[i]->write(all);
                IsSend = true;
            }
        }

        file.close();
        if(IsSend)
        {
            ui->record->append("<font color=\"#FF0000\"> 文件已转发完毕! </font> ");
        }
        else
        {
            ui->record->append("<font color=\"#FF0000\"> 文件转发失败，未有已连接的客户端! </font> ");
        }

        ui->msg->setText("");
        ui->sendFile->setEnabled("false");
        path = "";
    }
    else
    {
        ui->record->append("<font color=\"#FF0000\"> 文件发送失败，请检查文件路径是否正确！ </font> ");
        qDebug() << "文件发送失败 ";
    }

}
